$(function () {
  download();
  function download() {

    //1，找到详情页当前商品的id 
    var product_id = valueByName(location.search, 'product_id');
    //2,通过商品id，找到对应的商品
    $.ajax({
      type: 'get',
      url: './assets/data/goodsList.json',
      success: function (arr) {
        //通过product_id，找到想要的商品数据
        var goodsMsg = arr.find(item => item.product_id == product_id);

        //图片渲染
        var images = goodsMsg.images;
        //判断图片是不是一张
        if (images.length == 1) {
          $(`<img class='slider done' src="${goodsMsg.images}"
          style="float: none; list-style: none; position: absolute; width: 560px; z-index: 0; display: block;"
          alt="" />`).appendTo('#J_sliderView');
          //隐藏上一张下一张
          $('.ui-controls').hide();
        } else {
          for (var i = 0; i < images.length; i++) {
            $(`<img class='slider done' src="${goodsMsg.images[i]}"
            style="float: none; list-style: none; position: absolute; width: 560px; z-index: 0; display: ${i == 0 ? "block" : "none"};"
            alt="" />`).appendTo('#J_sliderView');

            $(`<div class='ui-pager-item'>
            <a href="#" data-slide-index="0" class='ui-pager-link ${i == 0 ? "active" : ""}'>1</a>
        </div>`).appendTo('.ui-wrapper .ui-controls .ui-pager');
          }
        }

        //页面数据渲染
        //产品介绍
        $(`<h1 class = 'pro-title J_proName'>
        <span class = 'img'></span>
        <span class = 'name'>${goodsMsg.name}</span>
    </h1>
    <!-- 提示 -->
    <p class = 'sale-desc' id = 'J_desc'>
        <font color="#ff4a00">${goodsMsg.title}</font>
        ${goodsMsg.product_desc_ext}
    </p>
    <div class = 'loading J_load hide'>
        <div class = 'loader'></div>
    </div>
    <!-- 主体 -->
    <div class = 'J_main'>
        <!-- 经营主题 -->
        <p class = 'aftersale-company' id = 'J_aftersaleCompany' type = '1' desc = 'null'>小米自营</p>
        <!-- 价格 -->
        <div class = 'pro-price J_proPrice'>
            <span class = 'price'>
            ${goodsMsg.price_max} 
                <del>${goodsMsg.market_price_max}</del>
            </span>
            <span class="seckill-notic hide"><em></em><i></i><span><span></span></span></span>
        </div><!-- 预售提示倒计时 -->
        <div class="pro-time hide J_proOrder">
            <div class='pro-time-head'>
                <span class='pro-order-count J_orderCount hide'></span>
                <span class='time J_orderTime'></span>
            </div>
            <div class='pro-time-con'>
                <span class='pro-time-price'>
                    ￥
                    <em class='J_orderPrice'></em>
                </span>
            </div>
        </div>
        <!-- 常态秒杀倒计时 -->
        <div class='pro-time J_proSeckill'>
            <div class="pro-time-head">
                <em class="seckill-icon"></em>
                <i>秒杀</i>
                <span class="time J_seckillTime">距结束 03 时 24 分 46 秒</span>
            </div>
            <div class='pro-time-con'>
                <span class='pro-time-price'>
                    ￥
                    <em class='J_seckillPrice'>${goodsMsg.price_max}</em>
                    <del>
                        ￥
                        <em class='J_seckillPriceDel'>${goodsMsg.market_price_max}</em>
                    </del>
                </span>
            </div>
        </div>`).prependTo('#J_buyBox .pro-choose-main .pro-info');

        //价格
        $(`<div class='pro-list' id='J_proList'>
        <ul>
            <li>${goodsMsg.name} &nbsp;${goodsMsg.value}
                <del>${goodsMsg.market_price_min}元</del>
                <span> ${goodsMsg.price_min}元 </span>
            </li>
            <li class="totlePrice" data-name="seckill">
                秒杀价 ：${goodsMsg.price_min}元
            </li>
        </ul>
    </div>`).insertBefore("#J_buyBox .pro-choose-main .pro-info .list-wrap #J_buyBtnBox");

    //加入购物车
      $(`<li>
      <a href="goodsCar.html"
          data-href="//order.mi.com/site/login?redirectUrl=https://item.mi.com/product/10000150.html"
          class="btn btn-primary btn-biglarge J_login" id="${goodsMsg.product_id}">加入购物车</a>
  </li>`).prependTo('#J_buyBtnBox');
      },
      error: function (msg) {
        console.log(msg);
      }
    })

  }
  banner();
  //轮播图
  function banner() {
    var iNow = 0; //默认第一张图片显示
    var aBtns = null; //获取所有小块按钮
    var aImgs = null; //获取所有图片
    var timer = null; //定时器

    timer = setInterval(function () {
      iNow++;
      tab();
    }, 3000);
    //点击按钮切换  事件委托
    $('.ui-pager').on("click", ".ui-pager-item a", function () {
      //获取当前点击的a的父节点的下标
      iNow = $(this).parent().index();
      tab();
      return false;

    })

    //给轮播图添加鼠标移入和鼠标移出效果
    $('#J_img').mouseenter(function () {
      clearInterval(timer);
    })
    $('#J_img').mouseleave(function () {
      timer = setInterval(function () {
        iNow++;
        tab();
      }, 3000);
    })

    //添加上一张下一张效果
    $(".ui-prev,.ui-next").click(function () {
      //上一张

      if (this.className == "ui-prev") {
        iNow--;
        if (iNow == -1) iNow = (aImgs.size() - 1);
      } else {
        iNow++;
      }
      tab();
      return false;
    })

    function tab() {
      if (!aImgs) {
        aImgs = $('#J_sliderView img');
      }
      if (!aBtns) {
        aBtns = $('.ui-pager .ui-pager-item a');
      }
      if (aImgs.size() == 1) {
        clearInterval(timer);
      } else {
        if (iNow == aBtns.size()) {
          iNow = 0;
        }
        aBtns.removeClass("active").eq(iNow).addClass("active");
        aImgs.hide().eq(iNow).show();
      }
    }
  }

  //给加入购物车按钮添加点击事件
  $('#J_buyBtnBox ').on("click",".J_login",function () {
    var id = this.id;
    var frist = $.cookie("goods") == null ? true : false;
    //如果是第一次添加
    if (frist) {
      var cookieArr = [{ id: id, num: 1 }];
      $.cookie("goods", JSON.stringify(cookieArr), {
        expires: 7
      })
    } else {
      var same = false; //假设之前没有添加过
      var cookieStr = $.cookie("goods"); //取出cookie里的数据
      var cookieArr = JSON.parse(cookieStr);
      for (var i = 0; i < cookieArr.length; i++) {
        if (cookieArr[i].id == id) {
          ///说明之前添加过
          cookieArr[i].num++;
          same = true;
          break;
        }
      }
      if (!same) {
        var obj = { id: id, num: 1 };
        cookieArr.push(obj);
      }
      //最后将数据存储在cookie里
      $.cookie("goods", JSON.stringify(cookieArr), {
        expires: 7
      })
    }

  })

  //封装一个获取当前加载详情的商品数据
  function valueByName(search, name) {
    //查找键的开始位置
    var start = search.indexOf(name + '=');
    if (start == -1) {
      return null;
    } else {
      var end = search.indexOf('&', start);
      if (end == -1) {
        end = search.length;
      }
      //提取想要的键值对
      var str = search.substring(start, end);
      var arr = str.split("=");
      return arr[1];
    }
  }
})